package com.tedu.zweibo.controller;


import com.tedu.zweibo.mapper.UserMapper;
import com.tedu.zweibo.pojo.dto.UserLoginDTO;
import com.tedu.zweibo.pojo.dto.UseregDRO;
import com.tedu.zweibo.pojo.entity.User;
import com.tedu.zweibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RequestMapping("/v1/users/")
@RestController
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("reg")
    @ApiOperation("用户注册")
    public int regUserDTO(@RequestBody UseregDRO userRegDTO){

        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        if(userMapper.selectByUsername(user.getUsername())==null){
            user.setCreated(new Date());

            userMapper.insert(user);
            return 1;
        }
        return 2;
    }
    @PostMapping("login")
    @ApiOperation("用户登录")
    public int login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.trace("UserController.login():begin");
        log.debug(userLoginDTO.toString());
        log.info("开始处理用户登录");
        User user=userMapper.selectByUsername(userLoginDTO.getUsername());
        if(user.getUsername()==null){
            return 3;
        }
        if(user.getPassword().equals(userLoginDTO.getPassword())){
            session.setAttribute("user",user);
            log.debug(user.toString());
            return 1;
        }else{
            return 2;
        }
    }
    @ApiOperation("查询在线状态")
    @GetMapping("currentUser")
    public UserVO currentUser(@ApiIgnore HttpSession session){
        User user=(User)session.getAttribute("user");
        System.out.println("查询");
        if(user==null){
            return null;
        }else{
            UserVO uservo=new UserVO();
            BeanUtils.copyProperties(user,uservo);
            return uservo;
        }
    }
    @ApiOperation("退出")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }

}
